<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-submit>
            <el-button :disabled="!canSubmit" @click="otherSubmit()"
              >提交</el-button
            >
          </template>
          <template v-slot:filter-store>
            <el-button :disabled="!canStore" @click="otherStore()"
              >入库</el-button
            >
          </template>
          <template v-slot:filter-revoke>
            <el-button :disabled="!canRevoke" @click="revoke()">撤回</el-button>
          </template>
          <template v-slot:filter-printQrCode>
            <el-button :disabled="!canPrintQrCode" @click="printCode()"
              >打印二维码</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </TableContainer>
    </div>

    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :order-id="modifyInfo.orderId"
      @returnModify="returnModify"
    />

    <Details
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.data"
      @returnBack="getList"
    />
    <ChosePrinter :visible="printerInfo.visible" @callBack="printerCallBack" />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <PageDialog
      v-show="excelOrPrintDialogInfo.visible"
      :title="excelOrPrintDialogInfo.title"
      v-model:visible="excelOrPrintDialogInfo.visible"
      :width="excelOrPrintDialogInfo.width"
      :bt-loading="excelOrPrintDialogInfo.btLoading"
      :bt-list="excelOrPrintDialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ excelOrPrintDialogInfo.msg }}：
        </div>
        <el-radio-group v-model="excelOrPrintDialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
    <!-- S 快捷上架弹窗 -->
    <SelectCargoSpace
      v-if="quickShelvingDialogInfo.visible"
      v-model:show-dialog="quickShelvingDialogInfo.visible"
      :check-box="false"
      title="请选择过渡货位"
      v-model:query="quickShelvingDialogInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="false"
      :showDepot="false"
      @callback="selectLocationNoCallBack"
    />
    <!-- E 快捷上架弹窗 -->
    <!-- S 上架任务弹窗 -->
    <PageDialog
      v-show="putShelfDialogInfo.visible"
      :title="putShelfDialogInfo.title"
      v-model:visible="putShelfDialogInfo.visible"
      :width="putShelfDialogInfo.width"
      :bt-loading="putShelfDialogInfo.btLoading"
      :bt-list="putShelfDialogInfo.btList"
      @reset="putShelfClose"
    >
      <PageForm
        v-model:ref-obj="putShelfFormInfo.ref"
        :data="putShelfFormInfo.data"
        :field-list="putShelfFormInfo.fieldList"
        :rules="putShelfFormInfo.rules"
        :label-width="putShelfFormInfo.labelWidth"
        :list-type-info="listTypeInfo"
      >
      </PageForm>
    </PageDialog>
    <!-- E 上架任务弹窗 -->
  </div>
</template>

<script setup name="storageStock">
import {
  printOrderListWsmStoreStockOrder,
  excelOrderListWsmStoreStockOrder,
  submitWsmStoreStockOrder,
  getWsmStoreStockOrderCustomizeList,
  wmsStoreStorePrintQrCode,
  executeWmsStoreOrder,
  createPutShelfOrder,
  getTransitionLocationByDeport,
  quickPutShelf,
} from '@/api/wms.js'
import Modify from './modify'
import Details from './details'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import {
  getRrgUserPage,
  fatchTemplateByCode,
  getRrgUserAll,
} from '@/api/base.js'
import DetailList from './detailList'
import _ from 'lodash'
import { getDepotAll, getUnitAll } from '@/api/core'
const { proxy } = getCurrentInstance()
const quickShelvingDialogInfo = ref({
  visible: false,
  query: {
    locationType: 2,
    status: 1,
    depotId: '',
  },
  id: '',
})

// 快捷上架弹窗
function quickShelving(row) {
  quickShelvingDialogInfo.value.visible = true
  quickShelvingDialogInfo.value.id = row.id
  quickShelvingDialogInfo.value.query.depotId = row.depotId
}
// 快捷上架过渡货位确认
function selectLocationNoCallBack(data) {
  let params = {
    id: quickShelvingDialogInfo.value.id,
    transition: data.id,
  }
  quickPutShelf(params).then((res) => {
    if (res && res.success) {
      quickShelvingDialogInfo.value.visible = false
      getList()
    }
  })
}

const putShelfDialogInfo = ref({
  visible: false,
  title: '请选择拆分类型及上架人',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '取消', event: putShelfClose, show: true },
    {
      label: '确认',
      type: 'primary',
      event: putShelfConfirm,
      show: true,
    },
  ],
})
//表单相关
const putShelfFormInfo = ref({
  ref: null,
  data: { putShelfUser: -2 },
  fieldList: [
    {
      label: '任务拆分类型',
      value: 'putSplitType',
      type: 'select-model',
      code: 'wms_put_split_type',
      checkDefault: true,
      required: true,
    },
    {
      label: '选择上架人',
      value: 'putShelfUser',
      type: 'select',
      list: 'userList',
      checkDefault: true,
      filterable: true,
    },
  ],
  rules: {
    putSplitType: [
      {
        required: true,
        message: '请选择任务拆分类型',
        trigger: ['blur'],
      },
    ],
  },
  labelWidth: '120px',
})
watch(
  () => putShelfFormInfo.value.data,
  (val) => {
    // 任务拆分类型-按产品拆分
    if (val.putSplitType == '1') {
      putShelfFormInfo.value.fieldList =
        putShelfFormInfo.value.fieldList.filter((element) => {
          return element.value !== 'putShelfUser'
        })
      putShelfFormInfo.value.data['putShelfUser'] = -2
    } else {
      // 任务拆分类型-不拆分（可选择用户）
      putShelfFormInfo.value.fieldList = addItem(
        putShelfFormInfo.value.fieldList,
        {
          label: '选择用户',
          value: 'putShelfUser',
          type: 'select',
          list: 'userList',
          clearable: false,
          filterable: true,
        }
      )
    }
    console.log(val)
  },
  { deep: true }
)
// 防止添加数组重复项
function addItem(items, item) {
  let foundObject = _.find(items, (e) => {
    return e.value === item.value
  })

  if (!foundObject) {
    items.push(item)
  }
  return items
}
// 上架任务弹窗
function putShelf(row) {
  getUserList(row)
}
// 关闭上架任务弹窗
function putShelfClose() {
  putShelfDialogInfo.value.visible = false
  proxy.$nextTick(() => {
    putShelfFormInfo.value.ref.resetFields()
  })
}
// 上架任务弹窗确认
function putShelfConfirm() {
  putShelfFormInfo.value.ref.validate((valid) => {
    if (valid) {
      savePutShelfUser()
    }
  })
}
//获取人员列表
function getUserList(row) {
  let params = {
    sort: 'create_time desc',
    idNotIn: row.putShelfUser || '',
    status: 1,
    isTransfer: 1,
    depotAuth: row.depotId,
  }
  getRrgUserAll(params).then((res) => {
    let arr = [{ key: '暂不选择', value: -2, userName: '' }]
    if (res && res.success) {
      if (res.data && res.data.length) {
        let data = res.data.map((item) => {
          return {
            key: item.name,
            value: item.id,
            userName: item.userName,
          }
        })
        listTypeInfo.value.userList = arr.concat(data)
        putShelfDialogInfo.value.visible = true
        putShelfDialogInfo.value.id = row.id
      } else {
        listTypeInfo.value.userList = arr
        putShelfDialogInfo.value.visible = true
        putShelfDialogInfo.value.id = row.id
      }
    }
  })
}
//导出提示相关配置
const excelOrPrintDialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: excelOrPrintHandleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    customizeUserVO: {},
    queryMap: {
      depotAuth: {
        asTbName: 'wms_store_stock_order',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
      deptAuth: {
        asTbName: 'wms_store_stock_order',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
    },
    queryParams: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      label: '打印',
      type: 'button',
      event: print,
      show: proxy.$permission('storageStock:printOrderList'),
    },
    {
      label: '导出excel',
      type: 'button',
      event: excel,
      show: proxy.$permission('storageStock:excelOrderList'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '快捷上架',
        event: quickShelving,
        show: proxy.$permission('storageStock:quickPutShelf'),
        ifRender: function (row) {
          return row.status === 3
        },
      },
      {
        label: '生成上架任务',
        event: putShelf,
        show: proxy.$permission('storageStock:createPutShelf'),
        ifRender: function (row) {
          return row.status === 3
        },
      },
      {
        label: '入库',
        event: otherStore,
        show: proxy.$permission('storageStock:store'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      /*  {
        label: '生成上架任务',
        event: createPutShelf,
        show: proxy.$permission('storageStock:createPutShelf'),
        ifRender: function (row) {
          return row.status === 3
        },
      }, */
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  orderId: '',
  title: '',
})
const detailInfo = ref({
  visible: false,
  data: {},
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const listTypeInfo = ref({
  userList: [],
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const canSubmit = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 1).length
  )
})
const canStore = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 2).length
  )
})
const canRevoke = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 2).length
  )
})
const canPrintQrCode = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter(
      (item) =>
        item.status !== 2 &&
        item.status !== 3 &&
        item.status !== 4 &&
        item.status !== 5
    ).length
  )
})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'storageStock' && el.url === val.url) {
                detailInfo.value.visible = false
                modifyInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  console.log(val)
                  proxy.$nextTick(() => {
                    detailInfo.value.visible = true
                    detailInfo.value.data = {
                      id: val.orderId,
                      orderNo: val.orderNo,
                      depotId: val.depotId,
                    }
                    sessionStorage.setItem('storeRowId', val.orderId)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

function pageInfo(obj) {
  page.value = obj
}
//打印
function print() {
  excelOrPrintDialogInfo.value.visible = true
  excelOrPrintDialogInfo.value.type = 'print'
  excelOrPrintDialogInfo.value.msg = '请选择数据打印范围'
  excelOrPrintDialogInfo.value.btList[1].label = '打印'
  excelOrPrintDialogInfo.value.flag = true
}
//导出
function excel() {
  excelOrPrintDialogInfo.value.visible = true
  excelOrPrintDialogInfo.value.type = 'excel'
  excelOrPrintDialogInfo.value.msg = '请选择数据导出范围'
  excelOrPrintDialogInfo.value.btList[1].label = '导出'
  excelOrPrintDialogInfo.value.flag = true
}
//打印或导出Excel
function checkConfirm() {
  if (excelOrPrintDialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (excelOrPrintDialogInfo.value.type === 'print') {
    printList()
  }
  excelOrPrintDialogInfo.value.visible = false
  excelOrPrintDialogInfo.value.msg = ''
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: excelOrPrintDialogInfo.value.flag,
  }
  excelOrderListWsmStoreStockOrder(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'storageStock:printOrderList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, excelOrPrintDialogInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag,
  }
  printOrderListWsmStoreStockOrder(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function excelOrPrintHandleClose() {
  excelOrPrintDialogInfo.value.visible = false
}

//上架
function savePutShelfUser() {
  let params = {
    id: putShelfDialogInfo.value.id,
    ...putShelfFormInfo.value.data,
  }
  createPutShelfOrder(params).then((res) => {
    if (res && res.success) {
      putShelfDialogInfo.value.visible = false
      getList()
    }
  })
}

function returnModify() {
  if (modifyInfo.value.orderId) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'wms_store_stock_order',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.value.orderId = row.id
  modifyInfo.value.title = '修改入库单'
  modifyInfo.value.visible = true
}
function otherSubmit(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  submitWsmStoreStockOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function otherStore(row = undefined) {
  executeWmsStoreOrder(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function printCode() {
  let ids = []
  for (let item of tableInfo.value.selections) {
    ids.push(item.id)
  }
  if (ids.length > 0) {
    wmsStoreStorePrintQrCode(ids).then((resp) => {
      if (resp && resp.success) {
        printerInfo.value.visible = true
        printerInfo.value.data = resp.data
      }
    })
  }
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.data = row
  console.log(99999)
  console.log(detailInfo.value.data)
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'wmsStoreStockOrder-com.slip.spd.entity.vo.wms.WmsStoreStockOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getWsmStoreStockOrderCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}

let obj = {
  typeValue: {
    label: '类型',
    value: 'typeValue',
    asValue: 'type',
    componentType: 'select-model',
    code: 'wms_store_type',
    show: false,
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'wms_store_stock_status',
    show: false,
    hidden: true,
  },
  depotName: {
    label: '出库仓库',
    value: 'depotName',
    asValue: 'depotId',
    componentType: 'slip-select',
    query: {
      depotAuth: 'id',
      status: 1,
      useTypeId: '1',
      isCargoSpaceManage: 1,
    },
    api: getDepotAll, //getDeptAll, getDepotAll, getSupplierAll
    show: false,
    hidden: true,
  },
  locationTypeValue: {
    label: '货位属性',
    value: 'locationTypeValue',
    asValue: 'locationType',
    componentType: 'select-model',
    code: 'goods_location_type',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
//getUserList()
</script>

<style scoped></style>
